package cn.edu.Bistu.wordsbook;

import android.content.Context;
import android.os.Bundle;


import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.fragment.app.ListFragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;


/**
 * A fragment representing a list of Items.
 */
public class WordsFragment extends ListFragment {


    private ArrayList<Map<String,String>> mWordList;


    public WordsFragment() {
    }


    @SuppressWarnings("unused")

    //生成fragment实例时将单词列表传入实例中
    public static WordsFragment newInstance(ArrayList<Map<String,String>> wordList) {
        WordsFragment fragment = new WordsFragment();
        Bundle args = new Bundle();
        args.putSerializable("list",wordList);   //设置参数后传入
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //获取参数
        if (getArguments()!=null){
            mWordList = (ArrayList<Map<String, String>>) getArguments().getSerializable("list");
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_words_list, container, false);

        // Set the adapter
        if (mWordList!=null){
        SimpleAdapter adapter = new SimpleAdapter(getActivity(),mWordList,R.layout.fragment_words,
                new String[]{Words.Word.COLUMN_WORD},
                new int[]{R.id.item_word});
        setListAdapter(adapter);
        }
        return view;
    }



    //当单词被点击时
    @Override
    public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Map<String,String> onClicked = mWordList.get(position);   //获取被点击的单词
        Bundle args = new Bundle();
        args.putSerializable("wordMap", (Serializable) onClicked);  //将单词绑定到Bundle里


        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        WordDetailsFragment wordDetailsFragment = new WordDetailsFragment();

        wordDetailsFragment.setArguments(args);   //传到WordDetailsFragment里
        fragmentTransaction.replace(R.id.detailsFrag,wordDetailsFragment).commit();  /**/



    }
}